#############################################/
## R-Script - Masterfile                    ##
## by: Schimpf, Wuttke, Schoen              ##
## Version: June 2023                       ##
## R-Version: 4.1.0.                        ##
#############################################/

#### /// BEFORE RUNNING THE SCRIPT ####

## 1) Create folder ("/PopStabilityReplication") and place all scripts and the 
##    dataset(s) in the folder.
## 2) Copy folder path into the following:
setwd("FOLDER PATH/PopStabilityReplication")

#### /// Load packages ####
#install (if necessary) and library required packages for all analyses
library("foreign")
library("stargazer")
library("MASS")
library("matrixStats")
library("reshape2")
library("ggplot2")
library("lavaan")
library("STARTS")
library("ggalluvial")
library("dplyr")
library("ggridges")
library("effsize")
# requires devtools: 
## Source: https://github.com/milanwiedemann/minvariance/
#devtools::install_github("milanwiedemann/minvariance")
library("minvariance")
library("stringr")
# Note: package minvariance was used to generate Lavaan syntax for MI tests.
# The package is not required to run the MI analyses.
library("lubridate")
library("grid")
library("ggpubr")

#### /// DATA WRANGLING ####

## NOTE: We work with a selected number of variables from the original dataset.
##       We used STATA to select the variables. All variables are original but
##       if you want to replicate the full process or want to add additional
##       variables, please see STATA DoFile (can also be opened in txt file.).
##       
##       The dataset we used here is the GLES Panel Dataset Version 5.0.0. We 
##       accessed the file on July 24, 2021. Full source:
##       GLES (2021): GLES Panel 2016-2021, Waves 1-15. GESIS Data Archive, 
##       Cologne. ZA6838 Data file Version 5.0.0,  https://doi.org/10.4232/1.13783
## FORE MORE INFORMATION - SEE ReadMe file

## Run the data wrangling file which includes recodes and deriving variables used in analyses
source("RScript_Recode_062023_Schimpfetal2023.R", verbose=F) 
#Clear the working space
rm(list=ls()) 


#### /// REPLICATE ANALYSIS ####

#### <<>> Read in recoded dataset ####
df_GLES17 <- read.csv("df_GLES17_recoded.csv",
                      stringsAsFactors=FALSE)


#### <<>> Invariance Test ####

##Invariance test cited in main text and explained in full in online appendix
source("R_Script_Invariance_Tests_Schimpfetal2023.R", verbose=F) 

#### <<>> Primary Analyses ####

## Replicates all analyses in main text and appendix, including Figures.
source("RScript_Analyses_062023_Schimpfetal2023.R", verbose=F) 


